package com.gmscosmo.janus.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * ClassName: EmailSender
 * Description: 邮件发送器
 * Date: 2021/2/24 16:05
 *
 * @author stephen.qiu
 */
@Component
public class EmailSender {
    @Autowired
    private EmailConfig emailConfig;

    private static Properties prop;

    @PostConstruct
    private void init() {
        prop = new Properties();
        prop.put("mail.host", "smtp.mxhichina.com");
        prop.put("mail.transport.protocol", "smtp");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.port", "465");
    }

    public void send(String msg) {
        if(!emailConfig.isSend()){
            return;
        }
        Session session = Session.getInstance(prop);
        session.setDebug(false);
        Transport ts;
        try {
            ts = session.getTransport();
            ts.connect(emailConfig.getEmailName(), emailConfig.getEmailPassword());
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(emailConfig.getEmailName()));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailConfig.getToEmail()));
            message.setSubject(emailConfig.getAvEngineTitle());
            message.setContent(msg, "text/html;charset=utf-8");
            ts.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
